'use client'

import React, { useState } from 'react';
import { Switch } from '@headlessui/react';
import DialogWrapper from './dialog-wrapper';
import { NotificationSettings } from '@/types/notification';
import { BellIcon, EnvelopeIcon, DevicePhoneMobileIcon } from '@heroicons/react/24/outline';

interface NotificationSettingsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  settings: NotificationSettings | null;
  onSave: (settings: NotificationSettings) => Promise<void>;
}

export default function NotificationSettingsDialog({
  isOpen,
  onClose,
  settings,
  onSave
}: NotificationSettingsDialogProps) {
  const [editedSettings, setEditedSettings] = useState<NotificationSettings | null>(settings);
  const [isSaving, setIsSaving] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  // 当settings变化时更新编辑状态
  React.useEffect(() => {
    setEditedSettings(settings);
    setSuccessMessage(null);
    setErrorMessage(null);
  }, [settings]);

  if (!editedSettings) return null;

  // 保存设置
  const handleSave = async () => {
    if (!editedSettings) return;
    
    setIsSaving(true);
    setSuccessMessage(null);
    setErrorMessage(null);
    
    try {
      await onSave(editedSettings);
      setSuccessMessage('通知设置已更新');
      
      // 成功后关闭对话框
      setTimeout(() => {
        onClose();
      }, 1500);
    } catch (error) {
      console.error('更新通知设置失败:', error);
      setErrorMessage('更新失败，请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  // 更新邮件通知设置
  const updateEmailSetting = (key: keyof NotificationSettings['email'], value: boolean) => {
    setEditedSettings(prev => {
      if (!prev) return prev;
      return {
        ...prev,
        email: {
          ...prev.email,
          [key]: value
        }
      };
    });
  };

  // 更新推送通知设置
  const updatePushSetting = (key: keyof NotificationSettings['push'], value: boolean) => {
    setEditedSettings(prev => {
      if (!prev) return prev;
      return {
        ...prev,
        push: {
          ...prev.push,
          [key]: value
        }
      };
    });
  };

  // 更新桌面通知设置
  const updateDesktopSetting = (key: keyof NotificationSettings['desktop'], value: boolean) => {
    if (key === 'enabled') {
      // 如果禁用桌面通知，则禁用所有桌面通知选项
      const newDesktopSettings = value
        ? { ...editedSettings.desktop, enabled: value }
        : {
            enabled: false,
            taskAssigned: false,
            taskComments: false,
            mentions: false,
            projectUpdates: false,
            teamChanges: false
          };
      
      setEditedSettings(prev => {
        if (!prev) return prev;
        return {
          ...prev,
          desktop: newDesktopSettings
        };
      });
    } else {
      setEditedSettings(prev => {
        if (!prev) return prev;
        return {
          ...prev,
          desktop: {
            ...prev.desktop,
            [key]: value
          }
        };
      });
    }
  };

  return (
    <DialogWrapper
      isOpen={isOpen}
      onClose={onClose}
      title="通知设置"
      size="md"
    >
      {successMessage && (
        <div className="mb-4 p-3 bg-green-50 border-l-4 border-green-500 text-green-700 rounded-md">
          <p>{successMessage}</p>
        </div>
      )}
      
      {errorMessage && (
        <div className="mb-4 p-3 bg-red-50 border-l-4 border-red-500 text-red-700 rounded-md">
          <p>{errorMessage}</p>
        </div>
      )}
      
      <div className="space-y-6">
        {/* 邮件通知 */}
        <div className="bg-white p-4 rounded-lg border border-gray-200">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <EnvelopeIcon className="h-6 w-6 text-gray-400" />
            </div>
            <div className="ml-3 flex-1">
              <h3 className="text-lg font-medium text-gray-900">邮件通知</h3>
              <p className="mt-1 text-sm text-gray-500">
                控制您希望通过邮件接收的通知类型
              </p>
              
              <div className="mt-4 space-y-4">
                <div className="flex items-center justify-between">
                  <label htmlFor="email-task-assigned" className="text-sm text-gray-700">任务分配</label>
                  <Switch
                    checked={editedSettings.email.taskAssigned}
                    onChange={(checked) => updateEmailSetting('taskAssigned', checked)}
                    id="email-task-assigned"
                    className={`${
                      editedSettings.email.taskAssigned ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.email.taskAssigned ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                <div className="flex items-center justify-between">
                  <label htmlFor="email-task-comments" className="text-sm text-gray-700">任务评论</label>
                  <Switch
                    checked={editedSettings.email.taskComments}
                    onChange={(checked) => updateEmailSetting('taskComments', checked)}
                    id="email-task-comments"
                    className={`${
                      editedSettings.email.taskComments ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.email.taskComments ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                <div className="flex items-center justify-between">
                  <label htmlFor="email-mentions" className="text-sm text-gray-700">提及我</label>
                  <Switch
                    checked={editedSettings.email.mentions}
                    onChange={(checked) => updateEmailSetting('mentions', checked)}
                    id="email-mentions"
                    className={`${
                      editedSettings.email.mentions ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.email.mentions ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                <div className="flex items-center justify-between">
                  <label htmlFor="email-project-updates" className="text-sm text-gray-700">项目更新</label>
                  <Switch
                    checked={editedSettings.email.projectUpdates}
                    onChange={(checked) => updateEmailSetting('projectUpdates', checked)}
                    id="email-project-updates"
                    className={`${
                      editedSettings.email.projectUpdates ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.email.projectUpdates ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                <div className="flex items-center justify-between">
                  <label htmlFor="email-weekly-digest" className="text-sm text-gray-700">每周摘要</label>
                  <Switch
                    checked={editedSettings.email.weeklyDigest}
                    onChange={(checked) => updateEmailSetting('weeklyDigest', checked)}
                    id="email-weekly-digest"
                    className={`${
                      editedSettings.email.weeklyDigest ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.email.weeklyDigest ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* 推送通知 */}
        <div className="bg-white p-4 rounded-lg border border-gray-200">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <DevicePhoneMobileIcon className="h-6 w-6 text-gray-400" />
            </div>
            <div className="ml-3 flex-1">
              <h3 className="text-lg font-medium text-gray-900">推送通知</h3>
              <p className="mt-1 text-sm text-gray-500">
                控制您希望通过移动设备接收的通知类型
              </p>
              
              <div className="mt-4 space-y-4">
                <div className="flex items-center justify-between">
                  <label htmlFor="push-task-assigned" className="text-sm text-gray-700">任务分配</label>
                  <Switch
                    checked={editedSettings.push.taskAssigned}
                    onChange={(checked) => updatePushSetting('taskAssigned', checked)}
                    id="push-task-assigned"
                    className={`${
                      editedSettings.push.taskAssigned ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.push.taskAssigned ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                <div className="flex items-center justify-between">
                  <label htmlFor="push-mentions" className="text-sm text-gray-700">提及我</label>
                  <Switch
                    checked={editedSettings.push.mentions}
                    onChange={(checked) => updatePushSetting('mentions', checked)}
                    id="push-mentions"
                    className={`${
                      editedSettings.push.mentions ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.push.mentions ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* 桌面通知 */}
        <div className="bg-white p-4 rounded-lg border border-gray-200">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <BellIcon className="h-6 w-6 text-gray-400" />
            </div>
            <div className="ml-3 flex-1">
              <h3 className="text-lg font-medium text-gray-900">桌面通知</h3>
              <p className="mt-1 text-sm text-gray-500">
                控制您希望在浏览器中接收的通知类型
              </p>
              
              <div className="mt-4 space-y-4">
                <div className="flex items-center justify-between">
                  <label htmlFor="desktop-enabled" className="text-sm text-gray-700">启用桌面通知</label>
                  <Switch
                    checked={editedSettings.desktop.enabled}
                    onChange={(checked) => updateDesktopSetting('enabled', checked)}
                    id="desktop-enabled"
                    className={`${
                      editedSettings.desktop.enabled ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                    } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                  >
                    <span
                      className={`${
                        editedSettings.desktop.enabled ? 'translate-x-6' : 'translate-x-1'
                      } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                    />
                  </Switch>
                </div>
                
                {editedSettings.desktop.enabled && (
                  <>
                    <div className="flex items-center justify-between">
                      <label htmlFor="desktop-task-assigned" className="text-sm text-gray-700">任务分配</label>
                      <Switch
                        checked={editedSettings.desktop.taskAssigned}
                        onChange={(checked) => updateDesktopSetting('taskAssigned', checked)}
                        id="desktop-task-assigned"
                        className={`${
                          editedSettings.desktop.taskAssigned ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                        } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                      >
                        <span
                          className={`${
                            editedSettings.desktop.taskAssigned ? 'translate-x-6' : 'translate-x-1'
                          } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                        />
                      </Switch>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <label htmlFor="desktop-mentions" className="text-sm text-gray-700">提及我</label>
                      <Switch
                        checked={editedSettings.desktop.mentions}
                        onChange={(checked) => updateDesktopSetting('mentions', checked)}
                        id="desktop-mentions"
                        className={`${
                          editedSettings.desktop.mentions ? 'bg-[var(--primary-color)]' : 'bg-gray-200'
                        } relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none`}
                      >
                        <span
                          className={`${
                            editedSettings.desktop.mentions ? 'translate-x-6' : 'translate-x-1'
                          } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
                        />
                      </Switch>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
      
      {/* 操作按钮 */}
      <div className="mt-6 flex justify-end space-x-3">
        <button
          type="button"
          className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
          onClick={onClose}
          disabled={isSaving}
        >
          取消
        </button>
        <button
          type="button"
          className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none disabled:opacity-50"
          onClick={handleSave}
          disabled={isSaving}
        >
          {isSaving ? '保存中...' : '保存'}
        </button>
      </div>
    </DialogWrapper>
  );
} 